const new_stu_row = document.getElementById("new_student");
const new_stu_button = document.getElementById("new_stu_row");
const delete_buttons = document.getElementsByClassName("delete_button");

new_stu_button.addEventListener("click", () => {
    const new_id = document.getElementById("stu_id");
    const new_name = document.getElementById("stu_name");
    const new_major = document.getElementById("major");
    if (new_stu_row.style.display === "none") {
        new_stu_button.textContent = "录入";
        new_stu_row.style.display = "flex";
        return;
    }
    new_stu_button.textContent = "新增";
    const message = {
        "update_type": "new_stu", "stu_id": new_id.value, "stu_name": new_name.value, "major": new_major.value,
    };
    new_id.value = "";
    new_name.value = "";
    new_major.value = "";


    fetch('hello-servlet', {
        method: 'POST', headers: {
            contentType: 'text/plain'
        }, body: JSON.stringify(message)
    }).then((response) => {
        if (response.ok) {
            alert("录入成功 请刷新页面");
            return;
        }
        alert("录入失败" + response.body);
    });


    new_stu_row.style.display = "none";

})

for (let index = 0; index < delete_buttons.length; index++) {
    const trigger = delete_buttons[index];
    trigger.addEventListener("click", () => {
        const raw = String(trigger.name);
        const raws = raw.split("__");
        if (raws.length !== 2) {
            alert("内部错误：学号解析失败");
            return;
        }
        const stu_id = raws[1];
        if (!confirm("确认删除学生" + stu_id + "?")) return;
        const message = {
            "update_type": "delete_button", "stu_id": stu_id.value,
        };
        fetch('hello-servlet', {
            method: 'POST', headers: {
                contentType: 'text/plain'
            }, body: JSON.stringify(message)
        }).then((response) => {
            if (response.ok) alert("录入成功"); else alert("录入失败" + response.body);
        });
    })
}



